<?
	//error_reporting (E_ALL ^ E_NOTICE);
	session_start();

	include('../../initDB.php');
	include('../../querys.php');
	include('../../functions.php');
	
	
	$_tags = $_REQUEST['tags'];
	$_link = $_REQUEST['link'];
	$_desc = $_REQUEST['desc'];
	$_date = $_REQUEST['date'];
	
	//$_tags = escape_string($_tags);
	$_link = escape_string($_link);
	$_desc = escape_string($_desc);
	$_date = escape_string($_date);
	
	
	echo  $_link . "<br>";
	echo $_tags . "<br>";
	echo $_desc . "<br>";
	echo $_date . "<br";
	
	
	//$splitted_tags = explode('|', $_tags);

	/*
	$tags = array();
	
	for($i = 0; $i < sizeof($splitted_tags); ++$i) {	
		$tags[$i] = array('name'=>$splitted_tags[$i], 'description'=>NULL);
	}*/
	
	$link = array(
			'dataA'=> $_date,	
			'linkValue'=> $_link,
			'description'=> $_desc, 
			'tags'=> $tags
			);
	
	$db_insert_link->execute(array(NULL, $link['dataA'], $link['linkValue'], $link['description']));
	
	
	$db_select_link_id->execute(array($link['linkValue']));
	$link_id = $db_select_link_id->fetch(); 
	$link_id = $link_id['id'];
	
	
	$retrieveUser->execute(array($_SESSION['user']));
	$user_id = $retrieveUser->fetch();
	$user_id = $user_id['id'];
	
	
	$db_insert_userLink->execute(array(NULL, $user_id, $link_id));
	
	foreach($_tags as $tag) {
	
		# check if the tag we're using is already defined in the db
		$db_select_tag_id->execute(array($tag)); 
		$result = $db_select_tag_id->fetchAll();
		$counter = count($result);
		if ($counter == 0) {
			$db_insert_tag->execute(array(NULL, $tag, ''));
			$db_select_tag_id->execute(array($tag));
			$result = $db_select_tag_id->fetchAll();
			}
		
		echo "tag: $tag counter: $counter ";
		$tag_id = $result[0]['id'];
		echo "tag_id: $tag_id";
		echo "link_id: $link_id ";  
		echo "\n\t\r";
		$db_insert_linkTag->execute(array(NULL, $link_id, $tag_id));
	}

	print_output($link);
?>